<template>
  <div class="login-container">
    <el-form class="login-form" autoComplete="on" :model="loginForm"
      :rules="activeName === 'LoginByPhone' ?  loginRules : loginCodeRules" ref="loginForm" label-position="left">
      <div class="login-logo">
        <img v-if="loginLogoUrl" :src="loginLogoUrl" alt="logo" class="height-130" border="0px">
      </div>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <div class="pad-l-12 pad-r-14 drag-on-box" v-show="dragBoolean">
          <div ref="dragDiv" class="drag-on">
            <div class="drag_bg"></div>
            <div class="drag_text">{{ confirmWords }}</div>
            <div ref="moveDiv" :class="{'handler_ok_bg':confirmSuccess}" style="position: absolute;top: 0px;left: 0px;"
              class="handler handler_bg" @mousedown="mousedownFn($event)"></div>
          </div>
        </div>
        <el-tab-pane label="密码登录" name="LoginByPhone">
          <div class="pad-l-12 pad-r-12 pad-t-8">
            <el-form-item prop="username">
              <el-input name="username" tabindex="1" type="text" maxlength="11" v-model="loginForm.phone"
                placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
                placeholder="密码" name="password" tabindex="2" autocomplete="on" @keyup.enter.native="handleLogin" />
              <span class="show-pwd" @click="showPwd">
                <svg-icon v-show="eyeType" class="icon-layer" icon-class="eye" />
                <svg-icon v-show="!eyeType" class="icon-layer" icon-class="eyeOpen" />
              </span>
            </el-form-item>
            <div v-if="showVerifyBar" class="position-r">
              <!-- <div class="position-r"> -->
              <div class="verify-bar" @click="onVerifyShow()">
                <img :src="verifyPic" alt="" class="width-330 height-50" border="0px">
              </div>
              <div class="slide-verify-bar" v-loading="loadingVerify" v-if="slideVerify">
                <slide-verify :l="42" :r="10" :w="310" :h="155" @success="onSuccess" @fail="onFail" @refresh="onRefresh"
                  :slider-text="text"></slide-verify>
              </div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="短信登录" name="LoginByPhoneAndSms">
          <div class="pad-l-12 pad-r-12 pad-t-8">
            <el-form-item prop="username">
              <el-input name="username" type="text" maxlength="11" v-model="loginForm.phone"
                @keyup.native="phoneEls(loginForm.phone)" placeholder="请输入手机号码" />
            </el-form-item>
            <el-form-item v-if="confirmSuccess">
              <div class="height-68"></div>
              <el-row>
                <el-col :span="16">
                  <el-input name="code" type="text" v-model="loginForm.smsCode" autoComplete="on" placeholder="填写验证码" />
                </el-col>
                <el-col :span="8" class="text-align-r">
                  <el-button class="code-btn" :loading="codeBtnLoading" :disabled="smsCodeDisabled" @click="getSmsCode">
                    {{ btnTxt }}
                  </el-button>
                </el-col>
              </el-row>
            </el-form-item>
          </div>
          <!-- <div class="height-50" v-if="confirmSuccess"></div> -->
          <div class="height-70" v-if="!confirmSuccess"></div>
        </el-tab-pane>
      </el-tabs>
      <div class="pad-l-12 pad-r-12">
        <div class="flex txt-bar pad-t-12 pad-b-15">
          <router-link tag="span" class="flex-item" to="/register">注册</router-link>
          <router-link tag="span" to="/forget-password">忘记密码？</router-link>
        </div>
        <el-button type="primary" class="login-btn" :loading="loading" :disabled="loginDisabled"
          @click.native.prevent="handleLogin(activeName)">登录
        </el-button>
      </div>
      <div class="text-align-c" v-if="false">
        <p class="type-t">第三方账号登录</p>
        <div class="login-type">
          <ul class="flex">
            <li class="wechat" @click="showWechatCode"></li>
          </ul>
        </div>
      </div>
    </el-form>
    <div class="tips">
      <span><a href="https://beian.miit.gov.cn/" target="_blank" ref="domainRecord"></a></span>
    </div>
    <div class="login-video-box" v-if="isVideo">
      <video class="login-video" id="login-video" autoplay="autoplay" preload="auto" loop="loop" muted="true"
        poster="https://enterpriseimg.joinsun.vip/images/video-pic.jpg">
        <source src="https://enterpriseimg.joinsun.vip/images/login3.mp4" type="video/mp4" />
        Your browser does not support the video tag.
      </video>
    </div>
    <div v-else :style="{background:'url('+loginBackgroundUrl+') no-repeat !important',}" class="login-img-box"></div>
  </div>
</template>

<script>
  import {
    isvalidatePhone
  } from '@/utils/validate'
  import config from '@/utils/config'
  import img_logo from '@/assets/images/login-logo.png'
  import verifyPic from '@/assets/images/verify-pic.png'
  import Cookies from 'js-cookie'
  import {
    getShowValidateCode,
    getValidateCode,
    sendSms,
    getConfigByDomain
  } from '@/api/login'

  export default {
    name: 'login',
    data() {
      const validatePhone = (rule, value, callback) => {
        if (!isvalidatePhone(value)) {
          callback(new Error('手机号码输入有误'))
        } else {
          callback()
        }
      }
      return {
        loginForm: {
          phone: '',
          password: ''
        },
        loginRules: {
          phone: [{
            required: true,
            trigger: 'blur',
            validator: validatePhone
          }],
          password: [{
            required: true,
            message: '密码不能为空',
            trigger: 'blur'
          }]
        },
        loginCodeRules: {
          phone: [{
            required: true,
            trigger: 'blur',
            validator: validatePhone
          }]
        },
        passwordType: 'password',
        loading: false,
        showDialog: false,
        img_logo: img_logo,
        verifyPic: verifyPic,
        eyeType: true,
        activeName: 'LoginByPhone',
        text: '向右滑',
        slideVerify: false,
        verifyCount: 0,
        loadingVerify: true,
        loginDisabled: true,
        smsCodeDisabled: true,
        codeBtnLoading: false,
        redirect: undefined,
        beginClientX: 0,
        mouseMoveStata: false,
        maxwidth: '',
        confirmWords: '拖动滑块验证',
        confirmSuccess: false,
        dragBoolean: true,
        btnTxt: '获取验证码',
        validateCode: '',
        showVerifyBar: false,
        wechatUrl: '',
        loginBackgroundUrl: '', // 登录页背景图
        loginLogoUrl: '', // logo图
        registerLogoUrl: '', // 注册页logo
        isVideo: false // 背景图是否是视频文件
      }
    },
    watch: {},
    mounted() {
      this.getConfigByDomain()
      this.maxwidth = this.$refs.dragDiv.clientWidth - this.$refs.moveDiv.clientWidth
      document.getElementsByTagName('html')[0].addEventListener('mousemove', this.mouseMoveFn)
      document.getElementsByTagName('html')[0].addEventListener('mouseup', this.moseUpFn)
      this.dragBoolean = false
      this.init()
    },
    methods: {
      // 获取背景图、logo信息
      getConfigByDomain() {
        const DOMAIN = window.location.host
        getConfigByDomain(DOMAIN).then(response => {
          const res = response.data
          this.loginBackgroundUrl = res.loginBackgroundUrl || config['LOGIN_BACKGROUND_URL']
          this.loginLogoUrl = res.loginLogoUrl || img_logo
          document.title = res.indexTitle || '众项云企'
          this.$pt.setStorageSync('document.title', document.title)
          this.$pt.setStorageSync('document.ico', res.indexIco)
          this.$refs.domainRecord.text = res.domainRecord || '©joinsun.vip 版权所有 备案许可证：闽ICP备19003459号'
          this.isVideo = this.parseURL(this.loginBackgroundUrl)
        }).catch(err => {
          console.log(err)
        })
      },
      // 获取url信息
      parseURL(url) {
        const aTag = document.createElement('a')
        aTag.href = url
        const TYPE = aTag.pathname.match(/([^/?#]+)$/i)[1]
        return TYPE.toLowerCase().indexOf('mp4') > -1
      },
      phoneEls(val) {
        if (isvalidatePhone(val)) {
          this.smsCodeDisabled = false
        } else {
          this.smsCodeDisabled = true
        }
      },
      getShowValidateCode() {
        getShowValidateCode({
          phone: this.$pt.getStorageSync('phone')
        }).then(response => {
          if (response.isError) return
          this.showVerifyBar = response.data.showValidate === 1
          this.validateCode = response.data.validateCode
          this.loginDisabled = this.showVerifyBar
          // 图片验证调试打开
          // this.showVerifyBar = true
        })
      },
      init() {
        this.getShowValidateCode()
        const redirectUrl = encodeURIComponent('https://e.joinsun.vip/api/system/user/wechat/auth')
        const stat = 'wx597837043c592bdc:login'
        this.wechatUrl = 'https://open.weixin.qq.com/connect/qrconnect?appid=wx597837043c592bdc&redirect_uri=' +
          redirectUrl + '&response_type=code&scope=snsapi_login&state=' + stat + '#wechat_redirect'
      },
      mousedownFn(e) {
        if (!this.confirmSuccess) {
          e.preventDefault && e.preventDefault()
          this.mouseMoveStata = true
          this.beginClientX = e.clientX
        }
      },
      successFunction() {
        // if (this.getValidateCode()) {
        this.confirmSuccess = true
        this.confirmWords = '验证通过'
        if (window.addEventListener) {
          document.getElementsByTagName('html')[0].removeEventListener('mousemove', this.mouseMoveFn)
          document.getElementsByTagName('html')[0].removeEventListener('mouseup', this.moseUpFn)
        } else {
          document.getElementsByTagName('html')[0].removeEventListener('mouseup', () => {})
        }
        document.getElementsByClassName('drag_text')[0].style.color = '#fff'
        document.getElementsByClassName('handler')[0].style.left = this.maxwidth + 'px'
        document.getElementsByClassName('drag_bg')[0].style.width = this.maxwidth + 'px'
        this.loginDisabled = false
        this.smsCodeDisabled = false
        // this.smsCodeDisabled = false
        // }
      },
      mouseMoveFn(e) {
        if (this.mouseMoveStata) {
          const width = e.clientX - this.beginClientX
          if (width > 0 && width <= this.maxwidth) {
            document.getElementsByClassName('handler')[0].style.left = width + 'px'
            document.getElementsByClassName('drag_bg')[0].style.width = width + 'px'
          } else if (width > this.maxwidth) {
            this.successFunction()
          }
        }
      },
      moseUpFn(e) {
        this.mouseMoveStata = false
        var width = e.clientX - this.beginClientX
        if (width < this.maxwidth) {
          const handler = document.getElementsByClassName('handler')[0]
          if (handler) {
            handler.left = '0px'
          }
          const dragBg = document.getElementsByClassName('drag_bg')[0]
          if (dragBg) {
            dragBg.width = '0px'
          }
        }
      },
      onVerifyShow() {
        this.loadingVerify = true
        this.slideVerify = !this.slideVerify
        setTimeout(() => {
          this.loadingVerify = false
        }, 1000)
      },
      onSuccess() {
        this.verifyCount += 1
        setTimeout(() => {
          this.slideVerify = false
        }, 600)
        if (this.getValidateCode()) {
          this.loginDisabled = false
        }
      },
      onFail() {
        this.loginDisabled = true
        this.text = '请重新尝试'
      },
      onRefresh() {},
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
          this.eyeType = false
        } else {
          this.passwordType = 'password'
          this.eyeType = true
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleClick() {
        if (this.activeName === 'LoginByPhoneAndSms') {
          this.dragBoolean = true
          this.loginDisabled = !this.confirmSuccess
        } else {
          this.dragBoolean = false
          this.loginDisabled = false
        }
      },
      getValidateCode() {
        if (!isvalidatePhone(this.loginForm.phone)) {
          this.$message.error('手机号码输入有误')
          return false
        }
        getValidateCode(this.loginForm.phone).then(response => {
          if (response.isError) return
          this.validateCode = response.data
        })
        return true
      },
      getSmsCode() {
        if (!isvalidatePhone(this.loginForm.phone)) {
          this.$message.error('手机号码输入有误')
          return
        }
        const that = this
        that.codeBtnLoading = true
        sendSms(this.loginForm.phone, this.validateCode, 1).then((response) => {
          that.codeBtnLoading = false
          if (response.isError) return
          that.time = 60
          that.timer()
          this.$message({
            message: '发送成功！',
            type: 'success'
          })
        }, (response) => {
          that.codeBtnLoading = false
          this.$message({
            message: '网络错误',
            type: 'error'
          })
        })
      },
      timer() {
        if (this.time > 0) {
          this.time--
          this.btnTxt = this.time + 's后重新获取'
          this.smsCodeDisabled = true
          setTimeout(this.timer, 1000)
        } else {
          this.time = 0
          this.btnTxt = '获取验证码'
          this.smsCodeDisabled = false
        }
      },
      doLogin(callback) {
        // 清除菜单缓存
        Cookies.set('mainMenu', '')
        Cookies.set('mainMenuRedirect', '')
        Cookies.set('mainMenuActiveName', '')
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.$pt.setStorageSync('phone', this.loginForm.phone)
            this.loading = true
            callback()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      handleLogin(type) {
        const that = this
        switch (type) {
          default:
          case 'LoginByPhone':
            this.doLogin(function() {
              that.getShowValidateCode()
              that.loginForm.validateCode = that.validateCode
              that.$store.dispatch('LoginByPhone', that.loginForm).then((enterprise) => {
                that.checkEnterpriseInfo(that, enterprise)
              }).catch(() => {
                that.loading = false
              })
            })
            break
          case 'LoginByPhoneAndSms':
            if (!this.loginForm.smsCode) {
              this.$message.error('请输入短信验证码')
              return
            }
            this.doLogin(function() {
              that.$store.dispatch('LoginByPhoneAndSms', that.loginForm).then((enterprise) => {
                that.checkEnterpriseInfo(that, enterprise)
              }).catch(() => {
                that.loading = false
              })
            })
            break
        }
      },
      checkEnterpriseInfo(that, enterprise) {
        that.loading = false
        if (enterprise.enterpriseName) {
          that.$router.push({
            path: '/'
          })
        } else {
          that.$router.push({
            path: '/register',
            query: {
              step: 2,
              enterpriseId: enterprise.enterpriseId,
              token: enterprise.token,
              versionType: enterprise.versionType,
              userCode: enterprise.userCode
            }
          })
        }
      },
      showWechatCode() {
        window.open(this.wechatUrl)
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  $bg: #283443;
  $light_gray: #000;

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 50px;
      width: 100%;
      margin-left: 0px;

      input::-webkit-input-placeholder {
        color: #999999;
      }

      input::-moz-placeholder {
        /* Mozilla Firefox 19+ */
        color: #999999;
      }

      input:-moz-placeholder {
        /* Mozilla Firefox 4 to 18 */
        color: #999999;
      }

      input:-ms-input-placeholder {
        /* Internet Explorer 10-11 */
        color: #999999;
      }

      input {
        background: #f4f4f4;
        border: 0px;
        -webkit-appearance: none;
        padding: 12px 12px 12px 12px;
        color: $light_gray;
        height: 50px;
        border-radius: 5px;
        font-size: 14px;
        border: 1px solid #dcdfe6;
        border-color: #dcdfe6;
        overflow: hidden;

        &:-webkit-autofill {
          border: 1px solid#dcdfe6;
          border-color: #dcdfe6;
          -webkit-box-shadow: 0 0 0px 1000px #f4f4f4 inset !important;
          -webkit-text-fill-color: #999999 !important;
        }

        &:focus {
          border-color: #dcdfe6 !important;
        }
      }
    }

    .el-form-item {
      // background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #fff;
      font-size: 20px;
      margin-bottom: 20px !important;
    }

    .code-btn {
      background: #409eff !important;
      border: 1px solid #409eff !important;
      color: #fff !important;
      border-radius: 10px !important;
      padding: 16px 0px;
      font-size: 12px;
      width: 115px;
      text-align: center;

      &:hover {
        background: #409eff;
        border: 1px solid #409eff;
        color: #fff;
      }

      &[disabled] {
        background: #cccccc !important;
        border: 1px solid #cccccc !important;
      }
    }
  }

  .login-container .el-form-item.is-success .el-input__inner {
    border-color: #dcdfe6 !important;
  }

  .drag-on-box {
    position: absolute;
    left: 0;
    top: 80px;
    width: 100%;
  }

  .drag-on {
    position: relative;
    background-color: #e8e8e8;
    width: 100%;
    height: 40px;
    line-height: 40px;
    text-align: center;
  }

  .handler {
    width: 40px;
    height: 40px;
    border: 1px solid #ccc;
    cursor: move;
  }

  .handler_bg {
    background: #fff url("") no-repeat center;
  }

  .handler_ok_bg {
    background: #fff url("") no-repeat center;
  }

  .drag_bg {
    background-color: #7ac23c;
    height: 40px;
    width: 0px;
  }

  .drag_text {
    position: absolute;
    top: 0px;
    width: 100%;
    text-align: center;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
    -o-user-select: none;
    -ms-user-select: none;
  }

  .verify-bar {
    background: #f4f2fa;
    height: 50px;
    border-radius: 5px;
    cursor: pointer;
    overflow: hidden;
  }

  .txt-bar {
    span {
      cursor: pointer;
      color: #aeaeae;
    }
  }

  .slide-verify-bar {
    position: absolute;
    background: #fff;
    padding: 4px;
    border: #dcdfe6 1px solid;
    left: 76px;
    bottom: -63px;

    &:before,
    &:after {
      position: absolute;
      left: -40px;
      top: 50%;
      margin-top: 8px;
      content: '';
      border-top: 18px transparent dashed;
      border-left: 20px transparent dashed;
      border-bottom: 18px transparent dashed;
      border-right: 20px #fff solid;
    }

    &:before {
      border-right: 20px #dcdfe6 solid;
    }

    &:after {
      left: -39px;
      border-right: 20px #fff solid;
    }
  }

  .login-form {
    min-height: 520px;

    .el-tabs__nav {
      margin-left: 12px;
    }

    .el-tabs__item {
      padding: 0 20px;
      font-size: 16px;
      color: #999999;
    }

    .el-tabs__item.is-active {
      color: #409EFF;
    }

    .el-tabs--top .el-tabs__item.is-top:nth-child(2) {
      padding: 0 20px 0 0px;
    }

    .el-tabs__content {
      overflow: visible;
    }
  }

  .type-t {
    color: #aeaeae;
  }

  .login-type {
    display: inline-block;
    margin-top: -5px;

    ul {
      margin: 0;
      padding: 0;
    }

    li {
      width: 42px;
      height: 42px;
      list-style: none;
      margin: 0 14px;
      cursor: pointer;
      background: url('../../assets/images/login-type-icon.png') no-repeat left top;

      &.wechat {
        background-position: 0 0;

        &:hover {
          background-position: 0 -46px;
        }
      }

      &.weibo {
        background-position: -46px 0;

        &:hover {
          background-position: -46px -46px;
        }
      }

      &.qq {
        background-position: -92px 0;

        &:hover {
          background-position: -92px -46px;
        }
      }
    }
  }
</style>

<style rel="stylesheet/scss" lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;

  @media screen and (max-width: 900px) {
    .login-form {
      margin: 0 auto !important;
    }

    .login-logo {
      margin-bottom: 68px !important;
      top: -185px !important;
      z-index: 30;
    }

    .login-video-box {
      z-index: 1;
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: #000002 url('https://enterpriseimg.joinsun.vip/images/video-pic-3.jpg') no-repeat center top;
      background-size: 900px 900px;

      .login-video {
        display: none;
      }
    }
  }

  .login-video {
    z-index: 1;
    position: absolute;
    top: 50%;
    left: 50%;
    min-width: 100%;
    min-height: 100%;
    object-fit: fill;
    /*这里是关键*/
    width: auto;
    height: auto;
    -ms-transform: translateX(-50%) translateY(-50%);
    -webkit-transform: translateX(-50%) translateY(-50%);
    transform: translateX(-50%) translateY(-50%);
    background-size: cover;
  }

  .login-img-box {
    background-size: 100%;
    width: 100%;
    height: 100vh;
  }

  .tips {
    position: fixed;
    left: 0;
    bottom: 0;
    font-size: 14px;
    text-align: center;
    color: #fff;
    margin-bottom: 10px;
    width: 100%;
    text-align: center;
    z-index: 5;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .login-container {
    position: fixed;
    height: 100%;
    width: 100%;
    background: #1d254d;

    .icon-layer {
      font-size: 21px;
      color: #dcdfe6;

      &.active {
        color: #dcdfe6 !important;
      }
    }

    .login-logo {
      width: 460px;
      margin-bottom: 68px;
      position: absolute;
      left: 0;
      top: -185px;
      z-index: 30;
    }

    .login-btn {
      width: 100%;
      margin-top: 13px;
      margin-bottom: 30px;
      background: #409eff;
      color: #fff;
      border-radius: 5px;
      font-size: 18px;
      padding: 15px 0 !important;

      &[loginDisabled] {
        border: #eeeeee 1px solid;
        color: #999999;
        background: #eeeeee;
        cursor: default;
      }
    }

    .login-form {
      position: absolute;
      left: 0;
      right: 0;
      top: 32.2%;
      width: 460px;
      padding: 18px 15px 14px 15px;
      box-sizing: border-box;
      margin: 0 auto;
      // margin: 264px auto 0 auto;
      background: #ffffff;
      border-radius: 5px;
      z-index: 10;
    }

    .svg-container {
      padding: 10px 5px 0 15px;
      color: $dark_gray;
      vertical-align: top;
      width: 30px;
      display: inline-block;
      position: absolute;
      left: 11px;
      top: -3px;
      z-index: 10;

      &_biz {
        top: -2px;
        left: 9px;

        .icon-layer {
          font-size: 26px;
        }
      }

      &_login {
        top: -2px;
        left: 8px;

        .icon-layer {
          font-size: 28px;
        }
      }
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        font-weight: 400;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }

      .set-language {
        color: #fff;
        position: absolute;
        top: 5px;
        right: 0px;
      }
    }

    .show-pwd {
      position: absolute;
      right: 22px;
      top: 7px;
      font-size: 16px;
      cursor: pointer;
      user-select: none;

      .icon-layer {
        color: #999999;
      }
    }

    .thirdparty-button {
      position: absolute;
      right: 35px;
      bottom: 28px;
    }
  }
</style>
